package com.infinitegroup.findmystuff.presenters;


import android.content.Context;

import com.infinitegroup.findmystuff.models.Item;
import com.infinitegroup.findmystuff.models.ItemLink;
import com.infinitegroup.findmystuff.views.AddItemView;

/**
 * Can add an item to the database based on the inputed information by the user.
 * 
 * @author Danielle
 *
 */
public class AddItemPresenter {
	
	private AddItemView view;
	private Item item;
	private String username;
	
	/**
	 * Constructor for the presenter
	 * @param view View associated with the activity the presenter controlls.
	 * @param username Username of the account currently logged into.
	 */
	public AddItemPresenter(AddItemView view, String username){
		this.view = view;
		this.username = username;
		item = new ItemLink((Context) view);	
	}
	
	/**
	 * Adds an item to the database based on the inputed strings; can also handle
	 * invalid inputs and notify the view of these invalidities.
	 * @param itemname Name of item
	 * @param location Location of item
	 * @param reward Reward for item
	 * @param description Description of item
	 * @param category Category of item
	 * @param status Status of item
	 * @return A boolean stating whether the addition of the item ws successful or not.
	 */
	public boolean handleAddItemClick(String itemname, String location, String reward, 
			String description, String category, String status){
		try{
			if (!(itemname.matches("[A-Za-z\\s]+"))){
				view.displayMessage("Please enter a valid Name.");
				return false;
			}
			if (!(location.matches("[A-Za-z\\s]+"))){
				view.displayMessage("Please enter a valid Location.");
				return false;
			}
			if (!(reward.matches("[0-9]+"))){
				view.displayMessage("Please enter a valid reward. Numbers only!");
				return false;
			}
			if (!(description.matches("[A-Za-z0-9.\\s]+"))){
				view.displayMessage("Please enter a valid description.");
				return false;
			}
			if (!(category.matches("(photos)|(jewelry)|(furniture)|(electronics)|(miscellaneous)"))){
				view.displayMessage("Please enter a valid Category.");
				return false;
			}
			if (status.equals("")){
				view.displayMessage("Please specify whether you lost or found this item");
				return false;
			}
			
			System.out.println(""+status+" "+category+" "+username);
			
			long id = item.insertNewItem(itemname, location, reward, description, status, category, username);
			
			if (id>0){
				view.displayMessage("Item added successfully");
				view.end();
				return true;
			} else {
				view.displayMessage("Errors encountered while entering item");
				return false;
			}
		} catch (Exception e){
			view.displayMessage("Could not Establish connection to server.");
			return false;
		}
	}	
	
	/**
	 * Handles click of cancel button by ending the activity.
	 */
	public void handleCancelClick(){
		view.end();
	}
}
